<template>
	<CustomNavBar title="发票抬头" />
	<view class="container">
		<scroll-view scroll-y class="title-list">
			<view v-if="titles.length === 0" class="empty-tip">暂无抬头信息</view>
			<view
				v-for="title in titles"
				:key="title.id"
				class="title-item"
				:class="{ 'active-card': title.isDefault }"
				@click="handleSelectTitle(title)"
			>
				<view class="item-header">
					<text class="name">{{ title.name }}</text>
					<view class="actions">
						<template v-if="selectMode">
							<uni-icons v-if="selectedTitleId === title.id" type="checkbox-filled" color="#1DCFB7" size="24"></uni-icons>
							<uni-icons v-else type="circle" color="#ccc" size="24"></uni-icons>
						</template>
						<view v-else class="edit-action" @click.stop="editTitle(title.id)">
							<uni-icons type="compose" size="18" color="#999"></uni-icons>
							<text class="edit-text">编辑</text>
						</view>
					</view>
				</view>
				<text class="tax-id">{{ title.taxId }}</text>
				<view class="item-footer">
					<view class="image-text_1">
						<radio :checked="title.isDefault" color="#1CCCB4" @click.stop="setDefault(title.id)" />
						<text class="text-group">设为默认</text>
					</view>
					<!-- <text class="divider">I</text>
					<text class="unbind-text" @click.stop="deleteTitle(title.id)">删除</text> -->
				</view>
			</view>
		</scroll-view>

		<view class="footer">
			<view class="tip">*发票抬头数量上限为5</view>
			<button class="add-btn" @click="addTitle">添加抬头</button>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import CustomNavBar from '@/components/CustomNavBar.vue';
import InvoiceApi from '@/api/app/invoice.js';

const titles = ref([]);

const selectMode = ref(false);
const selectedTitleId = ref(null);

// 监听保存事件：收到后刷新列表
const onTitleSaved = () => {
  loadTitles();
};

onLoad(async (options) => {
  if (options.selectMode) {
    selectMode.value = true;
  }
  await loadTitles();
  uni.$on('invoiceTitleSaved', onTitleSaved);
});

// 从编辑页 navigateBack 回来时，如果为保存返回则刷新
onShow(() => {
  const needs = uni.getStorageSync('invoiceTitleNeedsRefresh');
  if (needs) {
    uni.removeStorageSync('invoiceTitleNeedsRefresh');
    loadTitles();
  }
});

// 页面卸载时清理事件监听
onUnload(() => {
  uni.$off('invoiceTitleSaved', onTitleSaved);
});

const addTitle = () => {
  if (titles.value.length >= 5) {
    uni.showToast({ title: '发票抬头数量上限为5', icon: 'none' });
    return;
  }
	uni.navigateTo({ url: '/pages/invoice/title-edit' });
};

// 编辑：预取详情并通过事件通道传递到编辑页
const editTitle = async (id) => {
  if (!id) {
    uni.showToast({ title: '缺少ID', icon: 'none' });
    return;
  }
  try {
    uni.showLoading({ title: '加载中' });
    const res = await InvoiceApi.getInvoiceHeadDetail({ id });
    const detail = res?.data ?? res ?? {};
    uni.navigateTo({
      url: `/pages/invoice/title-edit?id=${id}`,
      success: (navRes) => {
        try {
          navRes.eventChannel.emit('initInvoiceTitle', detail);
        } catch (e) {
          // 事件通道不可用时忽略，编辑页会根据id自行兜底加载
        }
      }
    });
  } catch (e) {
    console.error('获取抬头详情失败:', e);
    uni.showToast({ title: '抬头详情加载失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 加载发票抬头列表并做字段映射
const loadTitles = async () => {
  uni.showLoading({ title: '加载中' });
  try {
    const res = await InvoiceApi.getInvoiceTitleList();
    const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : []);
    titles.value = list.map(item => ({
      id: item.id ?? item.headId ?? '',
      name: item.headerName ?? '',
      taxId: item.taxNo ?? '',
      isDefault: Boolean(item.isDefault),
      // 0 个人，1 企业
      type: item.titleType ?? null
    }));
  } catch (e) {
    console.error('获取发票抬头失败:', e);
    uni.showToast({ title: '发票抬头加载失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 设为默认：调用接口并更新本地状态
const setDefault = async (id) => {
  if (!id) {
    uni.showToast({ title: '缺少ID', icon: 'none' });
    return;
  }
  try {
    uni.showLoading({ title: '设置中' });
    await InvoiceApi.updateInvoiceHeads({ id, isDefault: 1 });
    titles.value = titles.value.map(t => ({ ...t, isDefault: t.id === id }));
    uni.showToast({ title: '已设为默认抬头', icon: 'none' });
  } catch (e) {
    console.error('设置默认失败:', e);
    uni.showToast({ title: '设置默认失败', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// 删除/解绑：弹窗确认后调用接口
// const deleteTitle = async (id) => {
//   if (!id) {
//     uni.showToast({ title: '缺少ID', icon: 'none' });
//     return;
//   }
//   uni.showModal({
//     title: '提示',
//     content: '确定要解绑该抬头吗？解绑后将无法使用该抬头开票',
//     success: async (res) => {
//       if (res.confirm) {
//         try {
//           uni.showLoading({ title: '处理中' });
//           await InvoiceApi.unbindInvoiceHeads({ id });
//           titles.value = titles.value.filter(t => t.id !== id);
//           uni.showToast({ title: '已解绑', icon: 'none' });
//         } catch (e) {
//           console.error('解绑失败:', e);
//           uni.showToast({ title: '解绑失败', icon: 'none' });
//         } finally {
//           uni.hideLoading();
//         }
//       }
//     }
//   });
// };

const handleSelectTitle = (title) => {
	if (selectMode.value) {
		selectedTitleId.value = title.id;
		uni.$emit('selectInvoiceTitle', title);
		uni.navigateBack();
	}
};

</script>

<style scoped>
.container {
    height: 90vh;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
}
.title-list {
    flex: 1;
    min-height: 0; /* 关键：允许滚动区域在flex布局中正确收缩，避免压住footer */
    background-color: #fff;
    width: 100%;
    box-sizing: border-box;
    padding: 30rpx;
    overflow-y: auto;
}
.title-item {
	background-color: #fff;
	border-radius: 10px;
	border: 1px solid #00C1A4;
	/* width: 688rpx; */
	align-self: center;
	margin-top: 30rpx;
	padding: 33rpx 25rpx 40rpx 29rpx;
	transition: border-color 0.3s;
}
.empty-tip {
	text-align: center;
	color: #999;
	font-size: 28rpx;
	/* padding: 120rpx 0; */
	padding-bottom: 12rpx;
}
.active-card { border: 1px solid #00C1A4 !important; }
.item-header { 
	margin-bottom: 15rpx;
	display: flex; 
	justify-content: space-between; 
	align-items: center; 
	}
.name {
	font-size: 38rpx;
	/* font-weight: 500; */
	line-height: 54rpx;
}
.tax-id {
	font-size: 27rpx;
	color: #7a7a7c;
}
.actions { display: flex; align-items: center; }
.edit-action { display: flex; align-items: center; }
.edit-text { margin-left: 8rpx; color: #999; font-size: 26rpx; }
.item-footer { 
	display: flex; 
	align-items: center; 
	margin-top: 30rpx; }
.image-text_1 { display: flex; align-items: center; }
.text-group { color: #000; font-size: 27rpx; line-height: 44rpx; margin-left: 10rpx; }
.divider { color: #7A7A7C; font-size: 31rpx; line-height: 44rpx; margin: 0 14rpx; }
/* .unbind-text { color: #79797B; font-size: 27rpx; line-height: 44rpx; } */
.footer {
    flex-shrink: 0;
    padding: 20rpx;
    /* border-top: 1px solid #DCDFEC; */
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    background-color: #fff;
    position: relative;
    z-index: 1; /* 确保不被滚动区覆盖 */
}
.add-btn {
	background-color: #1DCFB7;
	color: #fff;
	height: 88rpx;
	line-height: 88rpx;
	border-radius: 44rpx;
	font-size: 35rpx;
	width: 100%;
}
.tip {
	text-align: left;
	color: #999;
	font-size: 26rpx;
	margin: 0 0 35rpx;
	/* margin-top: 20rpx; */
}
</style>